package zmee.pur.src.common;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.orm.query.QFilter;
import kd.bos.orm.util.CollectionUtils;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.scm.common.util.ParamUtil;
import kd.scm.common.util.SrmCommonUtil;
import kd.scm.pds.common.change.IDataValidateService;
import kd.scm.pds.common.change.ValidateEvent;
import kd.scm.pds.common.change.ValidateResult;
import kd.scm.pds.common.enums.PdsLettersTypeEnum;
import kd.scm.src.common.enums.SrcProjectEnum;
import kd.scm.src.common.util.SrcWinruleUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: xw
 * @Date: 2023/03/08/9:44
 * @Description: 寻源变更--定标结果和份额变更条件
 */
public class SrcBidNumResValidateServiceExt implements IDataValidateService {
    private static final long serialVersionUID = 1L;

    public SrcBidNumResValidateServiceExt() {
    }

    @Override
    public ValidateResult validate(ValidateEvent validateEvent) {
        ValidateResult result = new ValidateResult();
        this.decisionIsAudit(result, validateEvent.getObj());
        this.validateChgData(validateEvent, result);
        return result;
    }

    public void decisionIsAudit(ValidateResult result, DynamicObject chgObj) {
        DynamicObject projectObj = chgObj.getDynamicObject("project");
        if (null == projectObj) {
            result.setMessage(ResManager.loadKDString("寻源项目为空，无法变更。", "SrcBidChangeUtil_8", "scm-src-common", new Object[0]));
            result.setSuccess(false);
        } else {
            DynamicObject purlistObject = QueryServiceHelper.queryOne("src_decision", "id,billstatus,bizstatus",
                    new QFilter[]{new QFilter("id", "=", projectObj.getPkValue())});
            String billStatus = purlistObject.getString("billstatus");
            if (SrcProjectEnum.AUDIT.getCode().equals(billStatus)) {
                result.setSuccess(true);
            }
        }
    }

    private void validateChgData(ValidateEvent validateEvent, ValidateResult result) {
        if (result.isSuccess()) {
            Map<String, Object> paramMap = validateEvent.getParams();
            if (!CollectionUtils.isEmpty(paramMap)) {
                Object decisionChgCompObj = paramMap.get("src_decisionchg");
                if (decisionChgCompObj instanceof DynamicObject) {
                    DynamicObject decisionCompData = (DynamicObject) decisionChgCompObj;
                    DynamicObjectCollection rows = decisionCompData.getDynamicObjectCollection("entryentity");
                    int rowCount = rows.size();
                    if (rowCount == 0) {
                        return;
                    }

                    if (!rows.stream().anyMatch((e) -> {
                        return e.getBoolean("isnew");
                    })) {
                        result.setMessage(ResManager.loadKDString("数据无变化，不需要提交。", "SrcBidNumResValidateService_4", "scm-src-common",
                                new Object[0]));
                        result.setSuccess(false);
                        return;
                    }

                    int unRecommandCount = 0;
                    Iterator var9 = rows.iterator();

                    while (var9.hasNext()) {
                        DynamicObject row = (DynamicObject) var9.next();
                        String result_New = row.getString("result_new");
                        if ("6".equals(result_New)) {
                            ++unRecommandCount;
                        }
                    }

                    if (rowCount == unRecommandCount) {
                        result.setMessage(ResManager.loadKDString("不能全部设置为不推荐。", "SrcBidNumResValidateService_1", "scm-src-common",
                                new Object[0]));
                        result.setSuccess(false);
                        return;
                    }
                }

                this.verifyOrderRatio(validateEvent, result);
            }
        }
    }

    private void verifyOrderRatio(ValidateEvent validateEvent, ValidateResult result) {
        if (result.isSuccess()) {
            StringBuilder materialName = new StringBuilder();
            Map<String, Object> paramMap = validateEvent.getParams();
            if (!CollectionUtils.isEmpty(paramMap)) {
                long projectId = SrmCommonUtil.getPkValue((DynamicObject) validateEvent.getObj().get("project"));
                if (SrcWinruleUtils.isNeedValidateOrderRatio(projectId)) {
                    Object decisionChgCompObj = paramMap.get("src_decisionchg");
                    if (decisionChgCompObj instanceof DynamicObject) {
                        DynamicObject decisionCompData = (DynamicObject) decisionChgCompObj;
                        DynamicObjectCollection rows = decisionCompData.getDynamicObjectCollection("entryentity");
                        String orderRatio = (String) ParamUtil.getParamObj("0DUM2+6E41IA", "orderratio");
                        List<String> orderRatioIndex =
                                Arrays.stream(orderRatio.split(",")).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
                        boolean orderRatioIsBreak = rows.stream().filter((row) -> {
                            return orderRatioIndex.contains(row.getString("result_new"));
                        }).anyMatch((e) -> {
                            return BigDecimal.ZERO.compareTo(e.getBigDecimal("orderratio_new")) == 0;
                        });
                        if (orderRatioIsBreak) {
                            String message = (String) orderRatioIndex.stream().map((str) -> {
                                return PdsLettersTypeEnum.fromVal(str).getName();
                            }).collect(Collectors.joining("/"));
                            result.setMessage(String.format(ResManager.loadKDString("%1$s供应商份额不能为空。", "SrcBidNumResValidateService_2",
                                    "scm-src-common", new Object[0]), message));
                            result.setSuccess(false);
                            return;
                        }

                        Map<String, List<DynamicObject>> packageNameMap = rows.stream().filter((row) -> {
                            return orderRatioIndex.contains(row.getString("result_new"));
                        }).collect(Collectors.groupingBy((row) -> {
                            return row.getString("package.id");
                        }));
                        Iterator var14 = packageNameMap.entrySet().iterator();

                        while (var14.hasNext()) {
                            Map.Entry<String, List<DynamicObject>> packageNameEntry = (Map.Entry) var14.next();
                            Map<String, List<DynamicObject>> materialNameMap =
                                    (Map) ((List<DynamicObject>) packageNameEntry.getValue()).stream().collect(Collectors.groupingBy((row) -> {
                                        return row.getString("purlist.id");
                                    }));
                            Iterator var17 = materialNameMap.entrySet().iterator();

                            while (var17.hasNext()) {
                                Map.Entry<String, List<DynamicObject>> materialNameEntry = (Map.Entry) var17.next();
                                BigDecimal sum = (BigDecimal) ((List<DynamicObject>) materialNameEntry.getValue()).stream().map((e) -> {
                                    return e.getBigDecimal("orderratio_new");
                                }).reduce(BigDecimal.ZERO, BigDecimal::add);
                                if (sum.compareTo(new BigDecimal(100)) != 0) {
                                    materialName.append(',').append(((DynamicObject) ((List) materialNameEntry.getValue()).get(0)).getString("purlist.materialnane"));
                                }
                            }
                        }

                        if (materialName.length() > 0) {
                            result.setMessage(String.format(ResManager.loadKDString("标的名称为%1$s的份额必须为100%2$s",
                                    "SrcBidNumResValidateService_3", "scm-src-common", new Object[0]), materialName.substring(1), "%!"));
                            result.setSuccess(false);
                        }
                    }

                }
            }
        }
    }
}
